<template>
  <div class="unitrooms">
    <Headline
      :headline1="$t('m.EquipmentCenter') + '  /  '"
      :headline2="$t('m.RoomSetting')"
    ></Headline>
    <a-card style="width：100%">
      <div class="search">
        <a-tree-select
          v-model="value"
          show-search
          style="width: 30%; height: 40px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="Please select"
          allow-clear
          @change="roomchecked"
          tree-default-expand-all
        >
          <a-tree-select-node
            v-for="item in roomitem"
            :key="item.id"
            :cont="item"
            :value="item.areaname"
            :title="item.areaname"
          >
            <a-tree-select-node
              v-for="int in item.children"
              :key="int.id"
              :cont="int"
              :value="int.areaname"
              :title="int.areaname"
            >
              <a-tree-select-node
                v-for="ins in int.children"
                :key="ins.id"
                :cont="ins"
                :value="ins.areaname"
                :title="ins.areaname"
              />
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
        <div class="btns">
          <a-button
            @click="addrooms"
            type="primary"
            style="width: 100%; height: 32px"
            v-if="isTrue('dev:area:house:add')"
          >
            {{ $t("m.NewRoom") }}
          </a-button>
        </div>
        <div class="btns">
          <a-button
            @click="batchrooms"
            type="primary"
            style="width: 100%; height: 32px"
            v-if="isTrue('dev:area:house:batchdel')"
          >
            {{ $t("m.Abatchofnew") }}
          </a-button>
        </div>
        <div class="btns">
          <a-button
            @click="deleterooms"
            type="primary"
            style="width: 100%; height: 32px"
            v-if="isTrue('dev:area:house:del')"
          >
            {{ $t("m.Abatchofdelete") }}
          </a-button>
        </div>
      </div>
      <div class="conter-table">
        <div id="components-table-demo-size">
          <a-table
            :rowKey="(record) => record.id"
            :columns="columns"
            :data-source="datas"
            bordered
            :pagination="false"
            :row-selection="{
              onChange: onSelectChange,
              selectedRowKeys: selectedRowKeysList,
            }"
          >
            <div slot="tags" slot-scope="text, tags, i">
              <a-button
                class="btn"
                type="primary"
                icon="diff"
                @click="roomchangeds(text, tags, i)"
                >{{ $t("m.Modification") }}</a-button
              >
              <a-button
                class="btn"
                type="danger"
                icon="diff"
                :disabled="!isTrue('dev:area:house:del')"
                @click="roomdeletes(text, tags, i)"
                >{{ $t("m.Delete") }}</a-button
              >
            </div>
          </a-table>
          <a-pagination
            class="pages"
            show-size-changer
            :defaultPageSize="5"
            :default-current="1"
            :total="total"
            @change="roomPages"
            :pageSizeOptions="['5', '10', '30', '40']"
            @showSizeChange="onShowRoomChange"
          />
        </div>
      </div>
    </a-card>
    <Modal :modal="madal" @modalLast="roomsOk" @modalhand="roomhand" >
      <a-form :form="forms">
        <div class="modolList">
         <a-form-item :label="$t('m.Floor')" class="flex-dev">
        <a-input-number
            v-decorator="['floors',{ rules: [{ required: true, message: '请输入楼层' }] },]"
            id="inputNumber"
          :placeholder="$t('m.PleaseEnterTheNameOfTheLevelMenus')"
          size="large"
          style="width: 300px; height: 32px"
          v-model="roomchanged.floors"
          :min="1"
        />
      </a-form-item>
      <a-form-item :label="$t('m.RoomName')" class="flex-dev">
        <a-input
            v-decorator="['areaName',{ rules: [{ required: true, message: '请输入房间名称' }] },]"
            :placeholder="$t('m.PleaseEnterTheNameroom')"
          size="large"
          style="width: 300px; height: 32px"
          v-model="roomchanged.areaName"
        />
      </a-form-item>
      </div>
      </a-form>
    </Modal>
    <Modal :modal="madals" @modalLast="batchOk" @modalhand="batchand">
       <a-form  :form="forms">
      <a-form-item style="display: flex" :label="$t('m.Area')">
        <a-input style="width: 500px" v-model="value" />
      </a-form-item>
      <div>{{ $t("m.Floornumberingrules") }}</div>
      <div class="olad">
        <a-form-item style="display: flex" :label="$t('m.Start')">
          <a-input-number
          v-decorator="['floorsStart',{ rules: [{ required: true, message: '请输入起始楼层编号' }] },]"
            id="inputNumber"
            v-model="roomserial.floorsStart"
            :min="1"
            :max="10"
          />
        </a-form-item>
        <a-form-item style="display: flex" :label="$t('m.End')">
          <a-input-number
          v-decorator="['floorsEnd',{ rules: [{ required: true, message: '请输入结束楼层编号' }] },]"
            id="inputNumber"
            v-model="roomserial.floorsEnd"
            :min="1"
            :max="10"
          />
        </a-form-item>
      </div>
      <div>{{ $t("m.Roomnumberingrules") }}</div>
      <div class="olad">
        <a-form-item style="display: flex" :label="$t('m.Start')">
          <a-input-number
              v-decorator="['roomStart',{ rules: [{ required: true, message: '请输入起始房间编号' }] },]"
            id="inputNumber"
            v-model="roomserial.roomStart"
            :min="1"
            :max="10"
          />
        </a-form-item>
        <a-form-item style="display: flex" :label="$t('m.End')">
          <a-input-number
              v-decorator="['roomEnd',{ rules: [{ required: true, message: '请输入结束房间编号' }] },]"
            id="inputNumber"
            v-model="roomserial.roomEnd"
            :min="1"
            :max="10"
          />
        </a-form-item>
      </div>
      <div>{{ $t("m.Resultsthepreview") }}</div>
      <a-textarea v-model="roomlist" placeholder="Basic usage" :rows="4" />
       </a-form>
    </Modal>
    <Delete ref="roomdelete" :dalete="dalete" @confirm="deteleroom"></Delete>
    <Delete
      ref="botahroomdelete"
      :dalete="daletes"
      @confirm="deteleroombotah"
    ></Delete>
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Modal from "@/components/common/Modal";
import Delete from "@/components/Delete";
import { roomIncrease } from "@/assets/js/tree";
import {
  getAreaTree,
  getRoomList,
  getBatchAddRoom,
  getSaveArea,
  getDelArea,
  delRoom,
} from "@/api/perUnit";
import { Setperms } from "@/assets/js/setperms";
export default {
  name: "Unitrooms",
  components: {
    Headline,
    Modal,
    Delete,
  },
  data() {
    return {
      checkNick: false,
      forms: this.$form.createForm(this, { name: 'dynamic_rule' }),
      selectedRowKeysList: [],
      madal: {
        visible: false,
        width: "600px",
        title: this.$t("m.NewRoom"),
      },
      madals: {
        visible: false,
        width: "600px",
        title: this.$t("m.Abatchofnew"),
      },
      dalete: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      daletes: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      total: 0,
      roomitem: [],
      value: "",
      columns: [
        {
          title: this.$t("m.WhereFloor"),
          dataIndex: "floors",
        },
        {
          title: this.$t("m.RoomName"),
          dataIndex: "areaname",
        },
        // {
        //   title: "完整名称",
        //   dataIndex: "areaname",
        // },
        {
          title: this.$t("m.Operation"),
          key: "tags",
          dataIndex: "address",
          scopedSlots: { customRender: "tags" },
        },
      ],
      datas: [],
      roomfrom: {
        parentId: 0,
        key: "",
        start: 0,
        limit: 5,
        page: 1,
      },
      roomchanged: {
        id: 0,
        areaCode: "",
        areaName: "",
        areaType: 3,
        parentId: "",
        status: 1,
        floors: "",
      },
      roomserial: {
        parentId: "",
        parentCode: "",
        parentSexArea: 3,
        floorsStart: '',
        floorsEnd: '',
        roomStart: '',
        roomEnd: '',
      },
      roomid: "", //删除房间id
      roomlist: "",
    };
  },
  created() {
    this._getAreaTree();
    this.parms = Setperms(
      this.$route.fullPath,
      JSON.parse(sessionStorage.getItem("menu"))
    );
    console.log(this.parms);
  },
  methods: {
    isTrue(str) {
      return this.parms.indexOf(str) !== -1;
    },
    _getAreaTree() {
      getAreaTree().then((res) => {
        if (res.status == 200) {
          this.$message.success("数据请求成功");
          this.roomitem = res.data;
          this._chexd();
        } else {
          this.$message.error("数据请求失败");
        }
      });
    },
    _getRoomList() {
      getRoomList({ params: this.roomfrom }).then((res) => {
        if (res.data.success) {
          console.log(res.data.data);
          this.$message.success("数据请求成功");
          this.datas = res.data.data;
          this.total = res.data.total;
        }
        console.log(res.data.data);
      });
      (this.roomchanged.areaName = ""), (this.roomchanged.floors = "");
    },
    roomchecked(value, label, extra) {
      console.log(extra.triggerNode);
      //判断是否选中值了
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        this.roomfrom.parentId = cont.id;
        this.roomchanged.parentId = cont.id;
        this.roomchanged.areaCode = cont.areacode;
        this.roomserial.parentId = cont.id;
        this.roomserial.parentCode = cont.areacode;
        // this.formlists.status = cont.status;
        this._getRoomList();
      }
    },
    _chexd() {
      //获取第一条数据
      let item = this.roomitem[0];
      console.log(item);
      this.value = item.areaname;
      this.roomfrom.parentId = item.id;
      this.roomchanged.parentId = item.id;
      this.roomchanged.areaCode = item.areacode;
      this.roomserial.parentId = item.id;
      this.roomserial.parentCode = item.areacode;
      this._getRoomList();
    },
    //新增房间
    addrooms() {
      setTimeout(() => {
        this.forms.setFieldsValue({
          floors:"",
          areaName:""
        })
      }, 200);

      this.madal.title = this.$t("m.NewRoom");
      this.madal.visible = true;
    },
    //修改
    roomchangeds(text, tags, i) {
      this.roomchanged.id = tags.id;
      this.roomchanged.floors = tags.floors;
      this.roomchanged.areaName = tags.areaname;
      this.madal.title = this.$t("m.EditRoom");
      this.madal.visible = true;
      this.roomchanged.areaCode = tags.areacode;
      this.roomchanged.parentId = tags.parentid;
      console.log(tags);
      setTimeout(() => {
        this.forms.setFieldsValue({
          floors:tags.floors,
          areaName:tags.areaname,
        })
      }, 200);
    },
    //修改确定
    roomsOk() {
      if(this.roomchanged.floors == "" && this.roomchanged.floors == ''&&
        this.roomchanged.areaName == ""&& this.roomchanged.areaName == ''
      ) {
        if (!err) {
          console.info('success');
          this.forms.resetFields();
        }
      }
      if(this.roomchanged.floors != "" && this.roomchanged.areaName != ""){
      getSaveArea(this.roomchanged)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getRoomList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.madal.visible = false;
      this.roomchanged.id = 0;
      this.roomchanged.areaCode = "";
      this.roomchanged.parentId = "";
      this.roomchanged.areaName = "";
      this.roomchanged.floors = "";
      }
    },
    //修改取消
    roomhand() {
      this.forms.resetFields();
      this.roomchanged.areaCode = "";
      this.roomchanged.parentId = "";
      this.roomchanged.areaName = "";
      this.roomchanged.floors = "";
    },
    //删除确定
    deteleroom() {
      getDelArea({ id: this.roomid })
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getRoomList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.roomdelete.visible = false;
    },
    //删除
    roomdeletes(text, tags, i) {
      this.$refs.roomdelete.visible = true;
      this.roomid = tags.id;
    },
    //批量增加
    batchrooms() {
      this.madals.visible = true;
    },
    onSelectChange(e) {
      this.selectedRowKeysList = e;
      console.log(this.selectedRowKeysList);
    },
    //批量删除
    deleterooms() {
      if (this.selectedRowKeysList.length > 0) {
        this.$refs.botahroomdelete.visible = true;
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
    deteleroombotah() {
      delRoom({ jsonData: JSON.stringify(this.selectedRowKeysList) }).then(
        (res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this.selectedRowKeysList = [];
            this._getRoomList();
          } else {
            this.$message.error(msg);
          }
        }
      );
      this.$refs.botahroomdelete.visible = false;
    },
    batchOk() {
      this.forms.validateFields(err => {
        if (!err) {
          this.forms.resetFields();
          this.roomlist = ''
          console.info('success');
        }
      });
      var data = this.roomserial
      if(data.floorsStart != "" && data.floorsEnd != "" && data.roomStart != "" && data.roomEnd != ""){
        getBatchAddRoom(this.roomserial)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getRoomList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.madals.visible = false;
      this.roomserial.floorsStart = "";
      this.roomserial.floorsEnd = "";
      this.roomserial.roomStart = "";
      this.roomserial.roomEnd = "";
      }
    },
    batchand() {
      this.forms.resetFields();
      this.roomlist = ''
      this.roomserial.floorsStart = "";
      this.roomserial.floorsEnd = "";
      this.roomserial.roomStart = "";
      this.roomserial.roomEnd = "";
    },
    //分页方法
    roomPages(page, limit) {
      this.roomfrom.page = page;
      this.roomfrom.limit = limit;
      this.roomfrom.start = (page - 1) * limit;
      this._getRoomList();
    },
    onShowRoomChange(page, pageSize) {
      this.roomfrom.page = page;
      this.roomfrom.limit = pageSize;
      this.roomfrom.start = (page - 1) * pageSize;
      this._getRoomList();
    },
  },
};
</script>

<style lang="scss" scoped>
.tableInput {
  border: 1px solid #d9d9d9;
  outline: none; // 去除选中状态边框
  border-radius: 3px;
  height: 30px;
  width: 300px;
  padding-left: 10px;
}
.tableInput::-webkit-input-placeholder {
  color: #d9d9d9;
}
.tableInput::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  color: #d9d9d9;
}
.flex-dev {
  display: flex !important;
  justify-content: center;
}
.search {
  display: flex;
  height: 35px;
}
.btns {
  margin-left: 15px;
}
.btn {
  width: 73px;
  font-size: 10px !important;
  margin-left: 15px;
}
.unitrooms .ant-table {
  margin-top: 30px;
}
.unitrooms .pages {
  margin-top: 15px;
}
.olad {
  display: flex;
  justify-content: space-evenly;
}
.modolList{
  display: flex;
  flex-wrap: wrap;
  width: 460px;
  justify-content: flex-end;
}
.conter-table{
  margin-top: 30px;
}
</style>
